package com.example.ktapplication.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.core.view.isGone
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.ktapplication.R
import com.example.ktapplication.adapter.CollectAdapter
import com.example.ktapplication.base.BaseActivity
import com.example.ktapplication.bean.CollectBeanDataX
import com.example.ktapplication.databinding.ActivityCollectBinding
import com.example.ktapplication.databinding.CollectContainerBinding
import com.example.ktapplication.enum.StateLayoutMode
import com.example.ktapplication.model.CollectViewModel
import com.example.ktapplication.state.CollectState
import com.example.ktapplication.utils.SpUtils
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.view.StatusLayout
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.eventbus.Subscribe
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CollectActivity :BaseActivity<ActivityCollectBinding>(), View.OnClickListener {

    private lateinit var mStatusLayout: StatusLayout
    var mContainer: View? = null
    private lateinit var loadingView: View
    private lateinit var emptyView: View
    private lateinit var errorView: View
    private lateinit var netView: View

    private lateinit var mRecyclerView: RecyclerView


    private var mJob: Job? = null

    private lateinit var collectModel: CollectViewModel
    var type: StateLayoutMode? = null

    var page:Int=0
    var isLoadMore: Boolean = false

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, CollectActivity::class.java)
            context.startActivity(intent)
        }
    }


    private val collectAdapter by lazy {
        CollectAdapter().apply {
            itemCallBack = object : CollectAdapter.OnItemClickListener {
                override fun onItemClick(bean: CollectBeanDataX) {
                    WebViewActivity.start(this@CollectActivity,bean.link,bean.title)
                }
            }
        }
    }

    override fun getViewBind(): ActivityCollectBinding {
        return ActivityCollectBinding.inflate(layoutInflater)
    }

    override fun onDate(savedInstanceState: Bundle?) {
        collectModel = ViewModelProvider(this)[CollectViewModel::class.java]
        initData(false)
        waithData()
    }

    ///加载数据
    private fun initData(isRefresh: Boolean) {
        lifecycleScope.launch(Dispatchers.IO) {
            collectModel.getHomeBannerData(page)
        }
    }

    private fun waithData() {
        mJob = lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            collectModel.state.collect { state ->
                when (state) {
                    is CollectState.OnSuccess -> {
                        if (state.collect != null) {
                            if (state.collect!!.errorCode == 0) {
                                if (state.collect!!.data.datas.isEmpty() && !isLoadMore) {
                                    type = StateLayoutMode.EMPTY
                                    showErroeView(type!!)
                                } else {
                                    withContext(Dispatchers.Main){
                                        binding.smartRefreshLayout.finishRefresh()
                                        binding.smartRefreshLayout.finishLoadMore()
                                        collectAdapter.addData(state.collect!!.data.datas,isLoadMore)
                                        mStatusLayout.addView(mContainer as View)
                                        mStatusLayout.setMode(StateLayoutMode.CONTENT)
                                    }
                                }
                            } else {
                                type = StateLayoutMode.ERROR
                                showErroeView(type!!)
                            }
                            state.collect!!.count += 1
                        }
                    }

                    is CollectState.OnError -> {
                        val error = state.exception!!.message
                        type = StateLayoutMode.ERROR
                        showErroeView(type!!)
                    }
                }
            }
        }
    }

    private fun showErroeView(type: StateLayoutMode) {
        lifecycleScope.launch(Dispatchers.Main) {
            binding.smartRefreshLayout.finishRefresh()
            binding.smartRefreshLayout.finishLoadMore()
            mStatusLayout.setMode(type)
        }
    }

    override fun onViewBing() {
        initTitleBar()
        initStatusLayou()
        initContainer()
        //上拉加载
        binding.smartRefreshLayout.setOnLoadMoreListener(object : OnLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                collectModel.getHomeBannerData(++page)
            }
        })
        //下拉刷新
        binding.smartRefreshLayout.setOnRefreshListener(object : OnRefreshListener {

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 0
                isLoadMore = false
                initData(false)
            }
        })
    }

    fun initContainer() {
        mContainer= layoutInflater.inflate(R.layout.collect_container, null)
        mRecyclerView = mContainer!!.findViewById<RecyclerView>(R.id.rvCollect)
        mRecyclerView.layoutManager =LinearLayoutManager(this@CollectActivity)
        mRecyclerView.adapter=collectAdapter
    }

    override fun isRegisterEvent(): Boolean {
        return true
    }

    private fun initTitleBar() {
        binding.titleBar.tvTitle?.text = "我的收藏"
        binding.titleBar.imgMenu?.apply {
            Glide.with(context)
                .load(R.mipmap.left)
                .into(this)
            setOnClickListener {
                finish()
            }
        }
        binding.titleBar.imgFind?.isGone = true
    }

    private fun initStatusLayou() {
        mStatusLayout=binding.statusLayout
        loadingView = layoutInflater.inflate(R.layout.status_layout_loading, null)
        mStatusLayout.setLoadingLayout(loadingView)
        emptyView = layoutInflater.inflate(R.layout.status_layout_empty, null)
        mStatusLayout.setEmptyLayout(emptyView)
        errorView = layoutInflater.inflate(R.layout.status_layout_error, null)
        mStatusLayout.setErrorLayout(errorView);
        netView = layoutInflater.inflate(R.layout.status_layout_net, null)
        mStatusLayout.setNetLayout(netView)
        emptyView.findViewById<LinearLayout>(R.id.btn_empty).setOnClickListener(this@CollectActivity);
        errorView.findViewById<LinearLayout>(R.id.btn_error).setOnClickListener(this@CollectActivity);
        mStatusLayout.setMode(StateLayoutMode.LOADING);
    }
    override fun onClick(p0: View?) {

    }

    override fun onDestroy() {
        super.onDestroy()
        mJob!!.cancel()
    }

    @Subscribe
    fun onLoginSuc(event: Event.LoginSuc) { //登录成功事件
        ///登录成功刷新界面，保存登录标记
        SpUtils.getInstance().setValue("LOGIN", true)

    }
}